<?php
    //初始化
    $curl = curl_init();
    //设置url
    curl_setopt($curl, CURLOPT_URL, 'http://iot-i.cn:9900/faas/mp3');
    //设置头文件的信息作为数据流输出
    //curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    // device id
    $device_id = "m_test_5c:cf:7f:87:db:0f";
    // mp3 file to read
    $mp3_file_name = 'test.mp3';
    $mp3_file_numb = '2';
    // 读取MP3文件并转换为base64字符串
    $mp3_content = base64_encode(file_get_contents($mp3_file_name));

    //设置post数据
    $post_data = array(
        "username" => "test",
        "passwd" => "test",
        "device_id" => $device_id,
        "mp3_name" => $mp3_file_numb,
        "mp3" => $mp3_content,
        "method" => "async_send", // 异步发送
    );
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
    //执行命令
    print_r("添加mp3文件\n");
    $data = curl_exec($curl);
    //显示获得的数据
    print_r($data);
    print_r("\n");

    print_r("获取下载进度,并等待是否完成\n");    
    $post_data = array(
        "device_id" => $device_id,
        "method" => "progress", 
    );
    while(true) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        //执行命令
        $data = curl_exec($curl);
        // 当前进度
        print_r($data); 
        $finish = $data->result;
        $success = $data->success;
        if(!$success) {
            break;
        }

        if($finish == "Failed") {
            break;
        }

        if($finish == 1){
            print_r("Download success!!!");
            break;
        }

        sleep(1);
    }

    print_r("\n");
    //关闭URL请求
    curl_close($curl);
?>
